package com.card.hwatt.service.impt;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.card.hwatt.dao.*;
import com.card.hwatt.dto.PageParam;
import com.card.hwatt.dto.PageResult;
import com.card.hwatt.dto.ReturnValue;
import com.card.hwatt.entity.*;
import com.card.hwatt.service.*;

@Service("holidayService")
public class HolidayServiceImpt extends BaseServiceImpt<Holiday> implements
		HolidayService {

	@Autowired
	@Qualifier("holidayDao")
	private HolidayDao dao;

	@Override
	protected BaseDao<Holiday> getDao() {
		return dao;
	}

	@Override
	public ReturnValue save(List<String> list) {
		if (CollectionUtils.isNotEmpty(list)) {
			String item = list.get(0);
			if (item.length() > 4) {
				String year = item.substring(0, 4);

				List<Object> params = new ArrayList<Object>();
				params.add(year + "%");

				PageResult<Holiday> delList = loadAll(new PageParam(0, 0,
						" id like ? ", params, " id desc "));
				if (delList != null && CollectionUtils.isNotEmpty(delList.rows)) {
					for (Holiday l : delList.rows) {
						dao.delete(l.id);
					}
				}
				String pattern = "yyyyMMdd";
				for (String string : list) {
					String[] parsePatterns = { "yyyy-M-d", "yyyy-MM-dd" };
					try {
						Date date = DateUtils.parseDate(string, parsePatterns);
						String id = DateFormatUtils.format(date, pattern);
						Holiday entity = new Holiday();
						entity.id = id;
						dao.save(entity);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

		ReturnValue result = new ReturnValue();
		result.isSucess = true;
		result.message = "ok";
		return result;
	}

	@Override
	public ReturnValue deleteYear(int year) {
		List<Object> params = new ArrayList<Object>();
		params.add(year + "%");

		PageResult<Holiday> delList = loadAll(new PageParam(0, 0,
				" id like ? ", params, " id desc "));
		if (delList != null && CollectionUtils.isNotEmpty(delList.rows)) {
			for (Holiday l : delList.rows) {
				dao.delete(l.id);
			}
		}

		ReturnValue result = new ReturnValue();
		result.isSucess = true;
		result.message = "ok";
		return result;
	}
}
